package cn.ug.account.service.impl;

import cn.ug.account.bean.AuthorizeBean;
import cn.ug.account.mapper.AuthorizeMapper;
import cn.ug.account.mapper.entity.Authorize;
import cn.ug.account.service.AuthorizeService;
import cn.ug.aop.RemoveCache;
import cn.ug.aop.SaveCache;
import cn.ug.bean.base.DataTable;
import cn.ug.bean.status.DeleteStatus;
import cn.ug.core.ensure.Ensure;
import cn.ug.service.impl.BaseServiceImpl;
import cn.ug.util.UF;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.StringUtils;
import org.dozer.DozerBeanMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

import static cn.ug.config.CacheType.OBJECT;
import static cn.ug.config.CacheType.SEARCH;

/**
 * @author kaiwotech
 */
@Service
public class AuthorizeServiceImpl extends BaseServiceImpl implements AuthorizeService {
	
	@Resource
	private AuthorizeMapper authorizeMapper;

	@Resource
	private DozerBeanMapper dozerBeanMapper;

	@Override
	@RemoveCache(cleanSearch = true)
	public int save(AuthorizeBean entityBean, String supLayer) {
		// 数据完整性校验
		if(null == entityBean || StringUtils.isBlank(entityBean.getActionValue()) || StringUtils.isBlank(entityBean.getName())) {
			Ensure.that(true).isTrue("11000101");
		}
		if(exists(entityBean, entityBean.getId())){
            // 该数据已存在
        	Ensure.that(true).isTrue("00000004");
        }
		Authorize entity = dozerBeanMapper.map(entityBean, Authorize.class);

		if(StringUtils.isBlank(entity.getId())) {
			entity.setId(UF.getRandomUUID());
		}
		// 设置级别
		entity.setLayer(findSelfLayer(supLayer));
		authorizeMapper.insert(entity);

        return 0;
	}

	@Override
	@RemoveCache(cleanSearch = true, cleanObjectByKeyPosition = 0)
	public int update(String id, AuthorizeBean entityBean) {
        // 数据完整性校验
		if(null == entityBean || StringUtils.isBlank(entityBean.getId()) || StringUtils.isBlank(entityBean.getActionValue()) || StringUtils.isBlank(entityBean.getName())) {
			Ensure.that(true).isTrue("11000101");
		}
		if(exists(entityBean, entityBean.getId())){
            // 该数据已存在
        	Ensure.that(true).isTrue("00000004");
        }
		Authorize entity = authorizeMapper.findById(entityBean.getId());
		dozerBeanMapper.map(entityBean, entity);

		authorizeMapper.update(entity);
		return 0;
	}

	@Override
	@RemoveCache(cleanSearch = true, cleanObjectByKeyPosition = 0)
	public int delete(String id) {
		if(StringUtils.isBlank(id)) {
			return 0;
		}

		return authorizeMapper.delete(id);
	}

	@Override
	@RemoveCache(cleanSearch = true, cleanObjectByKeyPosition = 0)
	public int deleteByIds(String[] id){
		if(id == null || id.length<=0){
			return 0;
		}

		return authorizeMapper.deleteByIds(id);
	}

	@Override
	@RemoveCache(cleanSearch = true, cleanObjectByKeyPosition = 0)
	public int removeByIds(String[] id) {
		if(id == null || id.length<=0){
			return 0;
		}

		return authorizeMapper.updateByPrimaryKeySelective(
				getParams()
						.put("id", id)
						.put("deleted", DeleteStatus.YES)
						.toMap()
		);
	}

	@Override
	@SaveCache(cacheType = SEARCH)
	public boolean exists(AuthorizeBean entityBean, String id) {
		if(null == entityBean || StringUtils.isBlank(entityBean.getActionValue())) {
			return false;
		}

		int rows = authorizeMapper.exists(
				getParams()
						.put("actionValue", entityBean.getActionValue())
						.put("id", id)
						.toMap()
		);
		return rows > 0;
	}

	@Override
	@SaveCache(cacheType = OBJECT)
	public AuthorizeBean findById(String id) {
		if(StringUtils.isBlank(id)) {
			return null;
		}

		Authorize entity = authorizeMapper.findById(id);
		if(null == entity) {
			return null;
		}

		AuthorizeBean entityBean = dozerBeanMapper.map(entity, AuthorizeBean.class);
		entityBean.setAddTimeString(UF.getFormatDateTime(entity.getAddTime()));
		entityBean.setModifyTimeString(UF.getFormatDateTime(entity.getModifyTime()));
		return entityBean;
	}

	@Override
	@SaveCache(cacheType = SEARCH)
	public List<AuthorizeBean> findList(String order, String sort, Integer status,String keyword) {
		return query(order, sort, status, keyword);
	}

	@Override
	@SaveCache(cacheType = SEARCH)
	public DataTable<AuthorizeBean> query(String order, String sort, int pageNum, int pageSize, Integer status,String keyword){
		Page<AuthorizeBean> page = PageHelper.startPage(pageNum, pageSize);
		List<AuthorizeBean> list = query(order, sort, status, keyword);
		return new DataTable<>(page.getPageNum(), page.getPageSize(), page.getTotal(), list);
	}

	@Override
	@RemoveCache(cleanSearch = true, cleanObjectByKeyPosition = 0)
	public int updateStatus(String[] id, Integer status) {
		if(id == null || id.length<=0){
			return 0;
		}

		return authorizeMapper.updateByPrimaryKeySelective(
				getParams()
						.put("id", id)
						.put("status", status)
						.toMap()
		);
	}

	/**
	 * 获取数据列表
	 * @param order			排序字段
	 * @param sort			排序方式 desc或asc
	 * @param status		状态	 0：全部 1：正常 2：禁用
	 * @param keyword		关键字
	 * @return				列表
	 */
	private List<AuthorizeBean> query(String order, String sort, Integer status,String keyword){
		List<Authorize> list = authorizeMapper.query(
				getParams(keyword, order, sort)
						.put("status", status)
						.toMap());
		return toBean(list);
	}

	@Override
	@SaveCache(cacheType = SEARCH)
	public List<AuthorizeBean> findListByLayer(String layer) {
		List<Authorize> list = authorizeMapper.findListByLayer(layer);
		return toBean(list);
	}

	@Override
	@SaveCache(cacheType = SEARCH)
	public List<AuthorizeBean> findListByRole(String roleId) {
		List<Authorize> list = authorizeMapper.findListByRole(roleId);
		return toBean(list);
	}

	@Override
	@SaveCache(cacheType = SEARCH)
	public List<AuthorizeBean> findListByPersonnel(String personnelId) {
		List<Authorize> list = authorizeMapper.findListByPersonnel(personnelId);
		return toBean(list);
	}

	private List<AuthorizeBean> toBean(List<Authorize> list) {
		List<AuthorizeBean> dataList = new ArrayList<>();
		if(null == list || list.isEmpty()) {
			return dataList;
		}
		for (Authorize o : list) {
			AuthorizeBean objBean = dozerBeanMapper.map(o, AuthorizeBean.class);
			objBean.setAddTimeString(UF.getFormatDateTime(o.getAddTime()));
			objBean.setModifyTimeString(UF.getFormatDateTime(o.getModifyTime()));
			dataList.add(objBean);
		}
		return dataList;
	}

	/**
	 * 计算新增节点级别
	 * @param supLayer	上级级别
	 * @return			新增节点级别
	 */
	private String findSelfLayer(String supLayer) {
		if(StringUtils.isBlank(supLayer)) {
			supLayer = "";
		}
		List<Authorize> aList = authorizeMapper.findListByLayer(supLayer);
		if(null == aList || aList.isEmpty()) {
			return supLayer + "100";
		}
		// 获取最大的一个节点
		String selfLayer = "";
		for(Authorize o : aList){
			if(StringUtils.isBlank(selfLayer) || selfLayer.compareTo(o.getLayer()) < 0){
				selfLayer = o.getLayer();
			}
		}
		if(StringUtils.isBlank(selfLayer ) || selfLayer.length() < 3) {
			return supLayer + "100";
		}

		String leftLayer = selfLayer.substring(0, selfLayer.length()-3);
		String maxNodeLayer = selfLayer.substring(selfLayer.length()-3);
		selfLayer = leftLayer + (UF.toInt(maxNodeLayer) + 1);
		return selfLayer;
	}
}

